import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CaseReviewService } from '../../../../../../@core/service/case-review/case-review.service';
import { DocgenService} from '../../../../../../@core/service/case-review/doc-select/api/docgen.service';
import { BizfileService } from '../../../../../../@core/service/case-review/doc-service/api/bizfile.service';
import {EvidenceService} from '../../../../../../@core/service/evidence/api/evidence.service';
import {TaskService} from '../../../../../../@core/service/task-serivce/api/task.service';
import { CaseDocService } from '../../../../../../@core/service/handle-service/api/caseDoc.service';
import {AllFileTypeGet } from '../interface';
import { DomSanitizer } from '@angular/platform-browser';  

import { NzMessageService } from 'ng-zorro-antd/message';
@Component({  
  selector: 'app-docfile',
  templateUrl: './docfile.component.html',
  styleUrls: ['./docfile.component.scss'],
})
export class DocfileComponent implements OnInit {
  /***********************查看证据详情*****************************/
  public isVisible = false;                     // 证据查看
  public isVisibleUpload = false;               // 证据上传
  public url = null;                            // 播放
  public loading = false;                       // 内容加载动画
  public choose: string;                        // 证据 文书判断条件
  public isOkLoading:boolean = false            // 确定按钮 loading
  public taskVisible:boolean = false            // 任务弹窗显示
  public taskmatter:any                         // 终端任务办理事项
  public describe:string                        // 终端下发描述
  // 是否展示文件列表
  // 证据上传案件环节
  public currentLinkUpload = null;

  // 证据查看
  public publictypeFlag = null;                 // 音视频图片判断
  public fileId: any = null;                    // 证据的文件ID

  public fileNameIndex = null;                  // 保存编辑按钮切换
  public newValue = null;                       // 编辑新内容值
  /***********************文书证据列表*****************************/
  private session = sessionStorage;             // 获取session值
  public FileType: string;                      // 选中文书类型
  public btnPerssion: any = {};                 // 按钮标识
  public AllFileType: AllFileTypeGet[] = [];    // 全部文书类型

  // 发送接收事件
  @Input() type;                                // 页面标识
  @Input() id;                                  // 父级页面id
  @Input() bizfileListOther;                    // 其他文书列表
  @Input() evidenceList;                        // 证据列表
  @Output() goRefinsh = new EventEmitter();     // 调用父组件刷新事件
  
  constructor(
    public docgen: DocgenService,               // 全部文书模版查询
    public caseReview: CaseReviewService,       // 文书审批模块
    public evidence: EvidenceService,           // 证据上传service
    public bizfile: BizfileService,             // 文书上传service
    public taskservice: TaskService,            // 下发终端任务
    public message:NzMessageService,            // 
    public caseDocService:CaseDocService,       // 
    private sanitizer: DomSanitizer
    ) { }

  ngOnInit() {
    this.AllFileTypeGet(); // 获取文书列表
    // 定义按钮权限
    if (this.type === 'approval') {
      this.btnPerssion = {
        insert: 'approval_document_insert',     // 新建文书
        upload: 'approval_document_upload',      // 文书上传
        select: 'approval_select',               // 查看
        evidence: 'approval_upload_evidence',    // 上传证据
        approval: 'approval_approval',           // 审批
        download: 'approval_upload',             // 下载
        delete: 'approval_delete',               // 删除
        choice: 'approval_choice_doc',           // 选择文书
      };
    } else {
      this.btnPerssion = {
        insert: 'handle_document_insert',     // 新建文书
        upload: 'handle_document_upload',      // 文书上传
        select: 'handle_select',               // 查看
        evidence: 'handle_upload_evidence',    // 上传证据
        approval: 'handle_approval',           // 审批
        download: 'handle_upload',             // 下载
        delete: 'handle_delete',               // 删除
        choice: 'handle_choice_doc',           // 选择文书
      };
    }
  }

  // 获取所有文书类型
  AllFileTypeGet(): void {
    this.docgen.docgenAllFiletypeGet().subscribe((data) => {
      this.AllFileType = data;
    });
  }

  // 创建文书 
  createdDoc() {
    if (this.FileType) {
      this.caseReview.setShowWindow(true);
      this.caseReview.getCreateCaseDoc().emit({
        condition: 'New',
        docid: null,
        doctype: this.FileType,
        bizid: this.id,
        callback:()=>{
          this.goRefinsh.emit({name:'bizfile'})
        }, 
      });
    }else{
      this.message.create('error','请选择文书类型！')
    }
  }
  // 显示下发终端模态框
  taskShow():void{
    this.taskVisible = true;
  }

  // 下发到终端
  sendTask():void{
    if(!this.taskmatter){
        this.message.create('error','请选择办理事项!')
        return;
    }
    if(!this.describe){
        this.message.create('error','请输入备注信息!')
        return;
    }
    this.isOkLoading = true;
    this.taskservice.sendTask({
      caseId: this.id,
      type:'案件办理',
      handleMatter:this.taskmatter,
      describe:this.describe,
      userId:sessionStorage.getItem('userId')
    }).subscribe((data:any)=>{
      this.isOkLoading = false 
      let { code, taskId }  = data;
      if(code && code == 1){
        this.message.create('error', `网络错误！`);
        return;
      }else if(taskId){
        this.message.create('success', `终端下发成功`);
        this.describe = '';
        this.taskmatter = null;
        this.taskVisible = false;
      }
    
    })
  }

  public  typeFlag:boolean =false;
  // 显示模态框
  showModal(contentType, fileId, condition): void {
    this.isVisible = true;
    this.fileId = fileId;
    this.publictypeFlag = contentType;

     // 证据查看
     if (condition === 'evidence') {
        this.evidence.evidenceFileIdGet(fileId).subscribe((res:any)=>{
          this.afterLoadMedia(res);
      },(error)=>{
        this.message.create('error','证据下载失败！')
      })

    // 文书查看  
    } else if (condition === 'bizfile') {
        this.bizfile.downloadFile(fileId).subscribe((res:any) => {
          this.afterLoadMedia(res);
        }, (error) => { 
          this.message.create('error','文书查询失败！')
          this.handleCancel();
        });
    // 终端数据查看    
    }
    if (contentType.includes('image') || contentType.includes('pdf')) {
      this.loading = true;
      const img = new Image();
      img.src = this.url;
      img.onload = () => {
        this.loading = false;
      };
    } else if (contentType.includes('audio')) {

    } else if (contentType.includes('video')) {

    }
  }

  // 视频音频加载后set操作
  afterLoadMedia(res){
    let url = URL.createObjectURL(res)
    this.url =  this.sanitizer.bypassSecurityTrustResourceUrl(url); 
    this.typeFlag = true;
  }


  handleOk(): void {
    this.isVisible = false;
  }
  handleCancel(): void {
    this.isVisible = false;
    this.loading = false;
    this.typeFlag = false;
  }

  // 证据 & 文书 上传弹框
  showModalUpload(choose): void {
    this.choose = choose;
    this.isVisibleUpload = true;
  }
  
  // 证据 & 文书 关闭按钮
  handleCancelUpload(): void {
    this.isVisibleUpload = false;
    this.fileNameIndex = null;
    this.newValue = null;

  }
  // 选择文件上传
  public customReq = (item: any) => {
    // Create a FormData here to store files and other parameters.
   this.fileNameIndex = null;
   if (this.choose === 'evidence') {
    this.evidence.evidenceFilePost(this.id, item.file, this.currentLinkUpload, this.session.getItem('userId')).subscribe((data) => {
      if (data.code === 200) {
        // this.fileList = data.data;
        this.goRefinsh.emit({name:'evidence'})
        this.currentLinkUpload = null;
      }
    });
   } else if (this.choose === 'bizfile') {
      this.bizfile.saveUploadBizFile(this.id, '其他', item.file.name, item.file, this.currentLinkUpload).subscribe((data) => {
        this.goRefinsh.emit({name:'bizfile'})
         if (data.code === 4) {
           
         }
      });
   }
 }
 
  // 删除 文件 & 证据单个数据
  deleteFile(id: string,docSource:string): void {
    if (this.choose === 'evidence') {
      if(docSource == '三方系统'){
        this.taskservice.deleteTaskFileStatus( id,  '1' ).subscribe((res)=>{
          if(res){
            
          }
        })
      }else{
        this.bizfile.deleteFileByFileid(id).subscribe((data: any) => {
          this.goRefinsh.emit({name:'evidence'})
        });
      }
    } else if (this.choose === 'bizfile') {
      if(docSource == '三方系统'){
        this.taskservice.deleteTaskFileStatus( id,  '1' ).subscribe((res)=>{
          if(res){
              
          }
        })
      }else{
        this.caseDocService.bizfileDelete("0",id,this.id).subscribe((data: any) => {
          this.goRefinsh.emit({name:'bizfile'})
        });
      }
    }
}


  //  下载证据
downloadEvidence(id: string) {
  this.evidence.evidenceFileIdGet(id).subscribe((data: any) => {

  });
}

changeTag(index, item) {
  this.fileNameIndex = index;
  const newnode = document.createElement('input');
  const oldnode =  document.getElementsByClassName('changedTag')[index];
  const fileHz = this.choose === 'bizfile' ? item.filename.substring(item.filename.lastIndexOf('.')) : oldnode.innerHTML.substring(oldnode.innerHTML.lastIndexOf('.'));  // 切除后缀
  newnode.value = oldnode.innerHTML.substring(oldnode.innerHTML.lastIndexOf('.'), -1);
  oldnode.parentNode.replaceChild(newnode, oldnode);
  newnode.focus();
  newnode.addEventListener('blur', () => {
  newnode.parentNode.replaceChild(oldnode, newnode);
  if ( newnode.value + fileHz === item.fileName) {
    this.fileNameIndex = null;
    } else {
    oldnode.innerHTML = newnode.value + fileHz;
    }
  this.newValue =  newnode.value + fileHz;
  });
}
  saveName(index, item) {
    // 保存方法
    item.fileName = this.newValue;
    if (this.choose === 'evidence') {
      this.evidence.evidencePut(item).subscribe((data: any) => {
        this.fileNameIndex = null;
        this.goRefinsh.emit({name:'evidence'})
        
      });
    } else if (this.choose === 'bizfile') {
      this.bizfile.modifyFileName(item.fileid, item.fileName).subscribe((data: any) => {
        this.fileNameIndex = null;
        this.goRefinsh.emit({name:'bizfile'})
      });
    }
  }
}
 